import { _decorator, AudioClip, AudioSource, Component, Event, EventTouch, JsonAsset, Label, Node, Prefab, SkeletalAnimation, tween, v3, Vec3 } from 'cc';
import { Panel, UIManager } from 'db://assets/Scripts/Framework/Managers/UIManager';
import { GameDataManager } from '../GameDataManager';
import { PoolManager } from 'db://assets/Scripts/Framework/Managers/PoolManager';
import NodeUtil from 'db://assets/Scripts/Framework/Utils/NodeUtil';
import Banner from 'db://assets/Scripts/Banner';
import { EasingType } from 'db://assets/Scripts/Framework/Utils/TweenUtil';
import { ProjectEventManager, ProjectEvent } from 'db://assets/Scripts/Framework/Managers/ProjectEventManager';
import { ChestItemUI } from './ChestItemUI';
const { ccclass, property } = _decorator;

@ccclass('MainUI')
export class MainUI extends Component {

    private static instance: MainUI;
    public static get Instance(): MainUI {
        return this.instance;
    }

    @property(Node)
    gamers: Node;

    @property(Node)
    weapons: Node;

    @property(Node)
    camera: Node;

    @property(Node)
    finish: Node;

    @property(Node)
    finish2: Node;

    @property(Node)
    rtSprite: Node;

    @property(Node)
    rookieBtn: Node;

    @property(Node)
    rookiePanel: Node;

    @property(Node)
    legendBtn: Node;

    @property(Node)
    legendPanel: Node;

    @property(Label)
    coinLabel: Label;

    @property(Label)
    DiamondLabel: Label;

    @property(AudioSource)
    audio: AudioSource;

    @property(JsonAsset)
    itemJson: JsonAsset;

    @property(Prefab)
    chestPrefab: Prefab;

    @property(AudioClip)
    click: AudioClip;

    @property(AudioClip)
    Bonus: AudioClip;

    @property([Node])
    panels: Node[] = [];

    @property([Node])
    reds: Node[] = [];

    rotateX = 0;
    model: Node;
    curWeapon: Node;
    headwears: Node;
    wings: Node;
    items: Record<string, any>;

    protected onLoad(): void {
        MainUI.instance = this;
        this.items = this.itemJson.json;
        ProjectEventManager.emit(ProjectEvent.返回主页);
    }

    start() {
        this._Init();
    }

    update(deltaTime: number) {

    }

    _Init() {
        this._InitToken();
        this._InitPlayer();
        this._InitRed();
        this._InitLogin();
        this._InitRotate(this.rtSprite);
        this._InitPack();
    }

    _InitToken() {
        let data = GameDataManager.Instance.getNumberData("Coin");
        this.coinLabel.string = data.toString();
        data = GameDataManager.Instance.getNumberData("Diamond");
        this.DiamondLabel.string = data.toString();
    }

    _InitPlayer() {
        let skinData = GameDataManager.Instance.getArrayData("UseSkin");
        for (let i = 0; i < this.gamers.children.length; i++) {
            const element = this.gamers.children[i];
            element.active = i == skinData[0];
        }
        this.model = this.gamers.children[skinData[0]];
        this.curWeapon = NodeUtil.GetNode("Hand", this.model);
        this.headwears = NodeUtil.GetNode("toutao", this.model);
        this.wings = NodeUtil.GetNode("chibang", this.model);
        if (this.headwears.children[0]) PoolManager.PutNode(this.headwears.children[0]);
        if (this.wings.children[0]) PoolManager.PutNode(this.wings.children[0]);
        if (skinData[2] >= 0) {
            let wing = this.items.Adorn[2][skinData[2]];
            PoolManager.GetNodeByBundle("MainPack", wing.prefab, this.wings);
        }
        if (skinData[1] >= 0) {
            let head = this.items.Adorn[1][skinData[1]];
            PoolManager.GetNodeByBundle("MainPack", head.prefab, this.headwears);
        }
        this._InitWeapon();
    }

    _InitWeapon() {
        this.camera.setRotationFromEuler(v3());
        let weaponData = GameDataManager.Instance.getArrayData("Weapon");
        let res = weaponData[0] == 5 ? this.items.Melee[weaponData[1]].prefab : this.items.Gun[weaponData[0]][weaponData[1]].prefab;
        if (this.curWeapon.children[0]) PoolManager.PutNode(this.curWeapon.children[0]);
        PoolManager.GetNodeByBundle("MainPack", res, this.curWeapon);
        let str = "持刀待机";
        if (weaponData[0] == 0) str = "手枪待机";
        else if (weaponData[0] < 5) str = "持枪待机";
        this.model.getComponent(SkeletalAnimation).crossFade(str);
    }

    _InitRed() {
        let dataArr = GameDataManager.Instance.getArrayData("LastDaily");
        let date = new Date;
        let isDaily = false;
        if (dataArr.length > 0 && dataArr[0] == date.getFullYear() && dataArr[1] == date.getMonth() && dataArr[2] == date.getDate()) isDaily = true;
        this.reds[0].active = !isDaily;
        let data = GameDataManager.Instance.getNumberData("IsGacha");
        this.reds[1].active = data == 0;
        dataArr = GameDataManager.Instance.getArrayData("Tasks");
        this.reds[2].active = false;
        for (let i = 0; i < dataArr.length; i++) {
            const element = dataArr[i];
            if (element == 0) {
                this.reds[2].active = true;
                break;
            }
        }
    }

    _InitLogin() {
        let lastDaily = GameDataManager.Instance.getArrayData("LastLogin");
        let date = new Date;
        let data = GameDataManager.Instance.getArrayData("Tasks");
        let data2 = GameDataManager.Instance.getArrayData("TaskRequires");
        if (!(lastDaily[0] == date.getFullYear() && lastDaily[1] == date.getMonth() && lastDaily[2] == date.getDate())) {
            lastDaily[0] = date.getFullYear();
            lastDaily[1] = date.getMonth();
            lastDaily[2] = date.getDate();
            GameDataManager.Instance.setArrayData("LastLogin", lastDaily);
            for (let i = 0; i < data.length; i++) { data[i] = 0; }
            for (let i = 0; i < data2.length; i++) { data2[i] = 0; }
            GameDataManager.Instance.setArrayData("Tasks", data);
            GameDataManager.Instance.setArrayData("TaskRequires", data2);
            GameDataManager.Instance.setNumberData("IsGacha", 0);
        }
    }

    _InitRotate(target: Node) {
        target.on(Node.EventType.TOUCH_START, this.RotateStart, this);
        target.on(Node.EventType.TOUCH_MOVE, this.RotateMove, this);
    }

    _InitPack() {
        let data = GameDataManager.Instance.getArrayData("AllSkin");
        this.rookieBtn.active = data[2][3] != 1;
        this.legendBtn.active = data[0][4] != 1;
    }

    RotateStart(event: EventTouch) {
        this.rotateX = event.getUILocation().x;
    }

    RotateMove(event: EventTouch) {
        let x = event.getUILocation().x;
        let delta = x - this.rotateX;
        let euler = this.gamers.eulerAngles.clone();
        euler.y += delta;
        this.gamers.setRotationFromEuler(euler);
        this.rotateX = x;
    }

    VideoCoin() {
        let x = this;
        Banner.Instance.ShowVideoAd(() => {
            let data = GameDataManager.Instance.getNumberData("Coin");
            data += 1000;
            GameDataManager.Instance.setNumberData("Coin", data);
            x._InitToken();
            UIManager.ShowTip("获得1000金币");
        })
        this.PlayClick();
    }

    VideoDiamond() {
        let x = this;
        Banner.Instance.ShowVideoAd(() => {
            let data = GameDataManager.Instance.getNumberData("Diamond");
            data += 500;
            GameDataManager.Instance.setNumberData("Diamond", data);
            x._InitToken();
            UIManager.ShowTip("获得500钻石");
        })
        this.PlayClick();
    }

    ShowPanel(event: Event) {
        let target: Node = event.target;
        let num = target.getSiblingIndex();
        this.panels[num].active = true;
        this.PlayClick();
    }

    Play() {
        UIManager.ShowPanel(Panel.LoadingPanel, ["PUBG", "Game"]);
        this.PlayClick();
    }

    FinishBtn() {
        tween(this.finish)
            .to(0.5, { scale: Vec3.ZERO }, { easing: EasingType.backIn })
            .start();
        this.PlayClick();
    }

    ShowFinish2(items: number[][]) {
        let layout = this.finish2.children[1].children[0];
        for (let i = 0; i < items.length; i++) {
            const element = items[i];
            let item = layout.children[i];
            if (!item) item = PoolManager.GetNodeByPrefab(this.chestPrefab, layout);
            item.getComponent(ChestItemUI).Init(element);
        }
        for (let i = items.length; i < layout.children.length; i++) {
            const element = layout.children[i];
            PoolManager.PutNode(element);
        }
        tween(this.finish2)
            .to(0.5, { scale: Vec3.ONE }, { easing: EasingType.backOut })
            .start();
        this.PlayBonus();
    }

    Finish2Btn() {
        tween(this.finish2)
            .to(0.5, { scale: Vec3.ZERO }, { easing: EasingType.backIn })
            .start();
        this.PlayClick();
    }

    PlayClick() {
        this.audio.playOneShot(this.click);
    }

    PlayBonus() {
        this.audio.playOneShot(this.Bonus);
    }

    ShowRookie() {
        this.rookiePanel.active = true;
        this.PlayClick();
    }

    ShowLegend() {
        this.legendPanel.active = true;
        this.PlayClick();
    }

}


